<template>
  <div class="tw-libchart xabsolute xwordcloud">
    <div v-show="data.length>0"
      class="tw-datasetchart"
      ref="chart"
      :style="{height: sheight, backgroundColor: bgColor}">
    </div>

    <tw-lib-nodata v-show="data.length===0" />
    <el-dialog :center="true" :model="false"
    :append-to-body="false"
    :modal-append-to-body="false"
    title="提示" custom-class="xdialog" :show-close="true"
    :visible.sync="dialogVisible"
    width="50%"
    :close-on-click-modal="false"
    :before-close="handleClose">
      <div slot="title" class="tw-dialog-title">
        <span></span><span style="font-size:12px"> （未掌握人数 -- {{dataList.length}}人）</span>
      </div>

      <div class="tw-dialog-body">
        <div class="tw-dialog-datalist" v-for="(item,index) in dataList" :key="index" :title="item.name">{{item.name}}</div>
      </div>
    </el-dialog>
    <!-- <div style="text-align:center">共<span style="">30</span>个薄弱知识点，<span>30</span>位学生没有掌握</div> -->
</div>
</template>

<script>
import props from './props'
import echarts from 'echarts'
import chartMixins from '../tw-lib-base/chart/chart'
import wordCloud from 'echarts-wordcloud/dist/echarts-wordcloud.min.js'

export default {
  name: 'chart-customized-wordcloud',

  mixins: [chartMixins],

  props,

  data() {
    return {
      dialogVisible: false,
      chartType: 'wordCloud',
      margintop: '15vh',
      isrun: false
    }
  },
  mounted () {
    const vm = this
    vm.$nextTick(() => {
      vm.init()
    })
  },

  computed: {
    sheight () {
      const vm = this

      if (vm.data.length === 0) {
        return vm.height
      }

      let maxlength = 0
      vm.data.forEach((item, index) => {
        maxlength += item.name.length
      })

      // let vmdata = []
      // maxlength  = 0
      // for (let i = 0; i < 40; i++) {
      //     this.data.forEach(item => {
      //       vmdata.push({
      //         name: item.name + i,
      //         value: item.value
      //       })
      //     })
      //   }

      // vmdata.forEach((item, index) => {
      //   maxlength += item.name.length
      // })

      // console.log('maxlength', maxlength)
      // console.log('maxlength', vm.maxSize)
      // console.log('maxlength', vm.minSize)
      // console.log('maxlength', parseInt(vm.width))

      const height = parseInt((maxlength * parseInt(vm.maxSize) * parseInt(vm.minSize)) / parseInt(vm.width)) - 2 * parseInt(vm.maxSize)
      // console.log(height)
      if (height > parseInt(vm.height)) {
        return height + 'px'
      } else {
        return vm.height
      }

      // if (parseInt(this.height) > document.documentElement.clientHeight * 0.6) {
      //   return this.height
      // } else {
      //   return Math.round(document.documentElement.clientHeight * 0.6) + 'px'
      // }
    }
  },

  methods: {
    setStyle () {
      const style = `
        ::root.tw-libchart.xwordcloud .el-dialog.xdialog {
          margin-top: ${this.margintop} !important;
        }
      `

      this.addStyle(style)
    },

    addStyle (style) {
      this.$el.classList.add(`x${this._uid}`)
      const styleEl = document.getElementById(this._uid) || document.createElement('style')
      styleEl.id = this._uid
      styleEl.innerText = style.replace(/::root/gm, `.x${this._uid}`).replace(/\n/gm, '')

      document.head.appendChild(styleEl)
    },
    getPoint (obj) {
      let t = obj.offsetTop
      let h = 100
      if (obj.style.height) {
        h = parseInt(obj.style.height) / 4
      }
      while (obj = obj.offsetParent) {
        t += obj.offsetTop
      }
      return t + h
    },
    init() {
      this.chart = echarts.init(this.$refs.chart)
      if (this.data.length > 0) {
        this.setOption().then(() => {
          this.isrun = false
          // vm.resize()
        })
      }
    },

    async setOption () {
      const vm = this
      if (this.data.length > 0 && !this.isrun) {
        vm.isrun = true
        let vmdata = []
        if (this.chart) {
          this.chart.clear()
        }
        let minSize = vm.minSize
        if (this.data.length <= 8) {
          minSize = vm.maxSize
        }

        vmdata = vm.data
        // for (let i = 0; i < 40; i++) {
        //   this.data.forEach(item => {
        //     vmdata.push({
        //       name: item.name + i,
        //       value: item.value
        //     })
        //   })
        // }

        const colorList = vm.colors

        // console.log(window.getComputedStyle(vm.$refs.chart).width)
        // console.log(document.documentElement.clientHeight)

        const height = Math.round(parseInt(vm.sheight) - 2 * parseInt(vm.maxSize)) + 'px'

        const option = {
          backgroundColor: vm.bgColor,
          tooltip: {
            show: vm.showTooltip,
            formatter: function(p) {
              if (vm.isSchoolExh) {
                return `使用次数：${
                  p.data.value
                }次`
              }
              return `未掌握人数：${
                p.data.value
              }人`
            }
          },
          series: [{
            type: this.chartType,
            gridSize: this.gridSize ? parseInt(this.gridSize) : 15,
            sizeRange: [parseInt(minSize), parseInt(vm.maxSize)],
            size: ['100%', '100%'],
            rotationRange: [0, 0],
            drawOutOfBound: vm.drawOutOfBound,
            shape: vm.shape,
            textStyle: {
              normal: {
                color: function() {
                  const index = Math.floor(Math.random() * colorList.length)
                  return colorList[index]
                }
                // color: function() {
                //   return 'rgb(' +
                //     Math.round(Math.random() * 255) +
                //     ', ' + Math.round(Math.random() * 255) +
                //     ', ' + Math.round(Math.random() * 255) + ')'
                // }
              }
            },
            left: 'center',
            top: 'center',
            width: this.$el.offsetWidth || vm.width,
            height: this.sheight,
            right: null,
            bottom: null,
            data: vmdata
          }]
        }
        if (!vm.icon) {
          vm.chart.clear()
          await vm.chart.setOption(option, true)
          if (vm.showDialog) {
            vm.chart.off('click')
            vm.chart.on('click', (params) => {
              const top = vm.getPoint(vm.$refs.chart)
              // console.log(top)
              vm.margintop = top + 'px'
              vm.setStyle()

              vm.$emit('input', params.name)
              vm.$emit('change', params.name)

              vm.dialogVisible = true
            })
          }
          vm.resize()
        } else {
          const maskImage = new Image()
          maskImage.src = vm.icon
          maskImage.onload = function () {
            const op = option.series[0]
            op.maskImage = maskImage
            vm.chart.clear()
            vm.chart.setOption(option, true)
            if (vm.showDialog) {
              vm.chart.off('click')
              vm.chart.on('click', (params) => {
                const top = vm.getPoint(vm.$refs.chart)
                // console.log(top)
                vm.margintop = top + 'px'
                vm.setStyle()

                vm.$emit('input', params.name)
                vm.$emit('change', params.name)
                vm.dialogVisible = true
              })
            }
            vm.resize()
          }
        }
      }
    },

    resize () {
      const vm = this
      // let height = Math.round(parseInt(vm.sheight))
      // console.log('height', this.sheight)
      // console.log('height', this.$el.offsetWidth)
      this.chart.resize({
        width: this.$el.offsetWidth || this.$ui.el.innerWidth(this.$el.parentElement) || parseInt(this.width),
        height: parseInt(this.sheight) || this.$el.offsetHeight
      })
    },

    handleClose () {
      // this.dataList = []
      this.dialogVisible = false
    }
  },

  watch: {
    sheight () {
      this.setOption().then(() => {
        this.isrun = false
      })
    },
    height () {
      this.setOption().then(() => {
        this.isrun = false
      })
    },
    width () {
      this.setOption().then(() => {
        this.isrun = false
      })
    },
    bgColor () {
      this.setOption().then(() => {
        this.isrun = false
      })
    },
    showTooltip () {
      this.setOption().then(() => {
        this.isrun = false
      })
    },
    minSize () {
      this.setOption().then(() => {
        this.isrun = false
      })
    },
    maxSize () {
      this.setOption().then(() => {
        this.isrun = false
      })
    },
    shape () {
      this.setOption().then(() => {
        this.isrun = false
      })
    },
    drawOutOfBound () {
      this.setOption().then(() => {
        this.isrun = false
      })
    },
    icon: {
      deep: true,
      handler () {
        this.setOption().then(() => {
          this.isrun = false
        })
      }
    },

    data: {
      deep: true,
      handler () {
        this.setOption().then(() => {
          this.isrun = false
        })
      }
    }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
